package com.sqx.modules.trends.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.BlockAndUserDao;
import com.sqx.modules.app.dao.SysEvaluateDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.SysEvaluate;
import com.sqx.modules.app.entity.vo.UserVO;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.goods.dao.GoodsDao;
import com.sqx.modules.goods.entity.Goods;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.trends.dao.TrendsDao;
import com.sqx.modules.trends.dao.TrendsTypeDao;
import com.sqx.modules.trends.entity.Trends;
import com.sqx.modules.trends.entity.TrendsType;
import com.sqx.modules.trends.service.ITrendsService;
import com.sqx.modules.trends.vo.TrendsVo;
import com.sqx.modules.trendsComment.dao.TrendsCommentDao;
import com.sqx.modules.trendsComment.entity.TrendsComment;
import com.sqx.modules.utils.BaiDuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户动态 服务实现类
 *
 * @author wuChang
 * @since 2023-09-26
 */
@Service
public class TrendsServiceImpl extends ServiceImpl<TrendsDao, Trends> implements ITrendsService {
    @Autowired
    private TrendsCommentDao trendsCommentDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private TrendsTypeDao trendsTypeDao;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private BlockAndUserDao blockAndUserDao;
    @Autowired
    private SysEvaluateDao sysEvaluateDao;
    @Autowired
    private TbOrdersDao tbOrdersDao;


    @Override
    public Result saveTrends(Trends trends) {
        String value = commonInfoService.findOne(332).getValue();
        if ("2".equals(value)) {
            if (StringUtils.isNotBlank(trends.getTrendsContent())) {
                if (BaiDuUtils.auditBaiDuText(trends.getTrendsContent())) {
                    return Result.error("您发布的内容包含敏感词汇");
                }
            }
            if (StringUtils.isNotBlank(trends.getTrendsImage())) {
                if (BaiDuUtils.auditBaiDuImg(trends.getTrendsImage())) {
                    return Result.error("您发布的图片不合规");
                }
            }
            if (trends.getTrendsId() != null) {
                return Result.upStatus(baseMapper.updateById(trends));
            } else {
                trends.setIsListing(1);
                trends.setBrowseCount(0);
                trends.setStatus(1);
                trends.setCreateTime(LocalDateTime.now());
                return Result.upStatus(baseMapper.insert(trends));
            }
        } else {
            if (trends.getTrendsId() != null) {
                return Result.upStatus(baseMapper.updateById(trends));
            } else {
                trends.setIsListing(2);
                trends.setBrowseCount(0);
                trends.setStatus(0);
                trends.setCreateTime(LocalDateTime.now());
                return Result.upStatus(baseMapper.insert(trends));
            }
        }
    }

    @Override
    public IPage<TrendsVo> getTrendsList(Integer page, Integer limit, Long byUserId, TrendsVo trendsVo) {
        Page<TrendsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TrendsVo> trendsVos = baseMapper.getTrendsList(pages, byUserId, trendsVo);
        for (TrendsVo record : trendsVos.getRecords()) {
            Goods goods = goodsDao.selectById(record.getGoodId());
            record.setGoods(goods);
        }
        return trendsVos;

    }

    @Override
    public Result getAllTrendsList(Integer page, Integer limit, Long byUserId, Long userId, Integer searchType, TrendsVo trendsVo) {
        Page<TrendsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        // 查询关注的人的动态列表 typeId是类型id
        if (searchType != null && searchType == 1 && trendsVo.getTypeId() != null) {
            return Result.success().put("data", baseMapper.getAllTrendsList(pages, byUserId, userId, trendsVo));
        } else if (searchType != null && searchType == 1) {
            return Result.success().put("data", baseMapper.getAllTrendsList(pages, byUserId, userId, trendsVo));
        }
        // 查询动态的列表 typeId是类型id
        if (searchType != null && searchType == 2 && trendsVo.getTypeId() != null) {
            return Result.success().put("data", baseMapper.getAllTrendsList1(pages, null, userId, trendsVo));
        } else if (searchType != null && searchType == 2) {
            return Result.success().put("data", baseMapper.getAllTrendsList1(pages, null, userId, trendsVo));
        }
        // 查询上新的列表
        if (searchType != null && searchType == 3) {
//            List<ScFollow> scFollows = trendsTypeDao.selectByUserId(userId);
//            List<TbFootprint> footprintList = trendsTypeDao.selectByFootprintList(userId);
//            // 用于存放用户已知的商品ID
//            Set<Long> allGoodIds = new HashSet<>();
//            // 用于存放商品类型ID
//            Set<Long> typeIds = new HashSet<>();
//
//            // 提取收藏的商品ID到Set中和类型ID
//            if (scFollows != null && !scFollows.isEmpty()) {
//                scFollows.forEach(scFollow -> {
//                    allGoodIds.add(scFollow.getById());
//                });
//                // 批量获取类型ID
//                List<Long> followTypeIds = goodsDao.getTypeIdsByGoodIds(new ArrayList<>(allGoodIds));
//                typeIds.addAll(followTypeIds);
//            }
//            // 从浏览过的商品中提取商品ID和类型ID
//            if (footprintList != null && !footprintList.isEmpty()) {
//                footprintList.forEach(footprint -> {
//                    allGoodIds.add(footprint.getGoodId());
//                });
//                // 批量获取类型ID
//                List<Long> footprintTypeIds = goodsDao.getTypeIdsByGoodIds(new ArrayList<>(allGoodIds));
//                typeIds.addAll(footprintTypeIds);
//            }
//            IPage<Goods> goods = baseMapper.getGoodsByTypeExcludingIds(pages, userId,null, null);
//            if (goods != null){
//                return Result.success().put("data", goods);
//            }else {
//                return Result.success().put("data", Collections.emptyList());
//            }

            // 查询类型下除了已知商品外的其他新商品
//            return Result.success().put("data", baseMapper.getGoodsByTypeExcludingIds(pages, typeIds, allGoodIds));
            return Result.success().put("data", baseMapper.getAllTrendsList2(pages, null, userId, trendsVo));
        }
        return Result.success().put("data", baseMapper.getAllTrendsList(pages, null, userId, trendsVo));
    }

    @Override
    public Result selectDynamicHomepage(Integer page, Integer limit, Integer type, Long userId, Long byUserId) {
        UserVO user = userDao.queryById(userId, byUserId);
        List<SysEvaluate> evaluates = new ArrayList<>();
        if (user != null) {
            if (type == 1) {
                page = (page - 1) * limit;
                Map<String, Object> params = new HashMap<>();
                params.put("byUserId", byUserId);
                params.put("page", page);
                params.put("limit", limit);
                user.setGoodsList(goodsDao.selectDynamicHomepage(params));
                user.setNeedCount(goodsDao.selectNeedCount(byUserId));
                List<TbOrders> ordersList = tbOrdersDao.selectList(new QueryWrapper<TbOrders>()
                        .eq("seller_id", byUserId)
                        .eq("retrieve_type", 1));
                if (!ordersList.isEmpty()) {
                    for (TbOrders tbOrders : ordersList) {
                        List<SysEvaluate> evaluateList = sysEvaluateDao.selectListByIndentNumber(params);
                        if (evaluateList != null) {
                            for (SysEvaluate sysEvaluate : evaluateList) {
                                if (sysEvaluate.getIndentNumber().contains(tbOrders.getOrderNumber()) && sysEvaluate.getUserId().equals(tbOrders.getBuyerId())) {
                                    evaluates.add(sysEvaluate);
                                }
                            }
                            user.setSysEvaluateList(evaluates);
                            user.setCommentsCount(sysEvaluateDao.selectCount(new QueryWrapper<SysEvaluate>()
                                    .eq("user_id", tbOrders.getBuyerId())
                                    .eq("recycle_status", 0)
                                    .eq("feedback_status", 1)));
                        }
                        user.setTotal(user.getGoodsCount());
                    }
                } else {
                    user.setSysEvaluateList(Collections.emptyList());
                    user.setCommentsCount(0);
                }
            } else if (type == 2) {
                page = (page - 1) * limit;
                Map<String, Object> params = new HashMap<>();
                params.put("byUserId", byUserId);
                params.put("page", page);
                params.put("limit", limit);
                user.setTrendsList(baseMapper.selectDynamicHomepage(params));
                if (user.getTrendsList() != null) {
                    for (Trends trends : user.getTrendsList()) {
                        Goods goods = goodsDao.selectById(trends.getGoodId());
                        trends.setGoods(goods);
                    }
                }
                List<TbOrders> ordersList = tbOrdersDao.selectList(new QueryWrapper<TbOrders>()
                        .eq("seller_id", byUserId)
                        .eq("retrieve_type", 1));
                if (!ordersList.isEmpty()) {
                    for (TbOrders tbOrders : ordersList) {
                        List<SysEvaluate> evaluateList = sysEvaluateDao.selectListByIndentNumber(params);
                        if (evaluateList != null) {
                            for (SysEvaluate sysEvaluate : evaluateList) {
                                if (sysEvaluate.getIndentNumber().contains(tbOrders.getOrderNumber()) && sysEvaluate.getUserId().equals(tbOrders.getBuyerId())) {
                                    evaluates.add(sysEvaluate);
                                }
                            }
                            user.setSysEvaluateList(evaluates);
                            user.setCommentsCount(sysEvaluateDao.selectCount(new QueryWrapper<SysEvaluate>()
                                    .eq("user_id", tbOrders.getBuyerId())
                                    .eq("recycle_status", 0)
                                    .eq("feedback_status", 1)));
                        } else {
                            user.setSysEvaluateList(Collections.emptyList());
                            user.setCommentsCount(0);
                        }
                    }
                } else {
                    user.setSysEvaluateList(Collections.emptyList());
                    user.setCommentsCount(0);
                }
                user.setNeedCount(goodsDao.selectNeedCount(byUserId));
                user.setTotal(user.getTrendsCount());
            } else {
                page = (page - 1) * limit;
                Map<String, Object> params = new HashMap<>();
                params.put("page", page);
                params.put("limit", limit);
                List<TbOrders> ordersList = tbOrdersDao.selectList(new QueryWrapper<TbOrders>()
                        .eq("seller_id", byUserId)
                        .eq("retrieve_type", 1));
                if (!ordersList.isEmpty()) {
                    for (TbOrders tbOrders : ordersList) {
                        params.put("userId", tbOrders.getBuyerId());
                        List<SysEvaluate> evaluateList = sysEvaluateDao.selectListByIndentNumber(params);
                        if (evaluateList != null) {
                            for (SysEvaluate sysEvaluate : evaluateList) {
                                if (sysEvaluate.getIndentNumber().contains(tbOrders.getOrderNumber()) && sysEvaluate.getUserId().equals(tbOrders.getBuyerId())) {
                                    evaluates.add(sysEvaluate);
                                }
                            }
                            user.setSysEvaluateList(evaluates);
                            user.setCommentsCount(sysEvaluateDao.selectCount(new QueryWrapper<SysEvaluate>()
                                    .eq("user_id", tbOrders.getBuyerId())
                                    .eq("recycle_status", 0)
                                    .eq("feedback_status", 1)));
                        } else {
                            user.setSysEvaluateList(Collections.emptyList());
                            user.setCommentsCount(0);
                        }
                    }
                } else {
                    user.setSysEvaluateList(Collections.emptyList());
                    user.setCommentsCount(0);
                }
                user.setTotal(user.getCommentsCount());
            }
            return Result.success().put("data", user);
        }
        return Result.error("用户不存在");
    }

    @Override
    public Result selectDynamicCount(Long userId, Long byUserId) {
        UserVO user = userDao.queryById(userId, byUserId);
        if (user != null) {
            // 查询订单列表
            List<TbOrders> ordersList = tbOrdersDao.selectList(new QueryWrapper<TbOrders>()
                    .eq("seller_id", byUserId)
                    .eq("retrieve_type", 1));

            if (!ordersList.isEmpty()) {
                // 提前计算总评论数
                List<String> orderNumberList = ordersList.stream().map(TbOrders::getOrderNumber).collect(Collectors.toList());
                int totalCommentsCount = sysEvaluateDao.selectCountByUserId(byUserId, orderNumberList);

                // 批量查询所有相关评价
                List<SysEvaluate> allEvaluates = sysEvaluateDao.selectList(new QueryWrapper<SysEvaluate>()
                        .in("user_id", ordersList.stream().map(TbOrders::getBuyerId).distinct().collect(Collectors.toList()))
                        .eq("recycle_status", 0)
                        .eq("feedback_status", 1));

                // 构建买家ID到评价列表的映射
                Map<Long, List<SysEvaluate>> evaluatesByUserId = allEvaluates.stream()
                        .collect(Collectors.groupingBy(SysEvaluate::getUserId));

                // 更新用户的评论信息
                user.setCommentsCount(totalCommentsCount);
                user.setSysEvaluateList(evaluatesByUserId.getOrDefault(byUserId, Collections.emptyList()));
            } else {
                // 如果没有订单，则设置默认值
                user.setCommentsCount(0);
                user.setSysEvaluateList(Collections.emptyList());
            }
            return Result.success().put("data", user);
        }
        return Result.error("用户不存在");
    }

    @Override
    public Result selectDynamicGoods(Integer page, Integer limit, Long userId, Long byUserId) {
        Page<Goods> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<Goods> goodsList = goodsDao.queryPageByUserId(pages, byUserId);
//        goodsList.getRecords().forEach(goods -> {
//            goods.setNeedCount(goodsDao.selectNeedCount(byUserId));
//        });
        return Result.success().put("data", goodsList);
    }

    @Override
    public Result selectDynamicTrends(Integer page, Integer limit, Long userId, Long byUserId) {
        IPage<Trends> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<Trends> trendsList = baseMapper.selectTrendsWithGoodsAndCounts(pages, byUserId);
//        trendsList.getRecords().forEach(trends -> {
//            Goods goods = goodsDao.selectById(trends.getGoodId());
//            trends.setGoods(goods);
//            trends.setLikeCount(baseMapper.selectByLikeCount(byUserId, trends.getTrendsId()));
//            trends.setCommentsCount(baseMapper.selectByCommentCount(byUserId, trends.getTrendsId()));
//        });
        return Result.success().put("data", trendsList);
    }

    @Override
    public Result selectDynamicComments(Integer page, Integer limit, Long userId, Long byUserId) {
        List<TbOrders> ordersList = tbOrdersDao.selectList(new QueryWrapper<TbOrders>()
                .eq("seller_id", byUserId)
                .eq("retrieve_type", 1));
        if (!ordersList.isEmpty()) {
            for (TbOrders tbOrders : ordersList) {
                // 设置默认分页参数
                if (page == null || page < 1) {
                    page = 1;
                }
                if (limit == null || limit < 1) {
                    limit = 10;
                }
                // 构建包含所有买家ID的集合
                Set<Long> buyerIds = ordersList.stream().map(TbOrders::getBuyerId).collect(Collectors.toSet());

                page = (page - 1) * limit;
                Map<String, Object> params = new HashMap<>();
                params.put("userId", buyerIds);
                params.put("byUserId", byUserId);
                params.put("page", Math.max(0, (page - 1) * limit));
                params.put("limit", limit);
                List<SysEvaluate> evaluateList = sysEvaluateDao.selectAllEvaluationsBySellerAndBuyers(params);
                if (evaluateList != null) {
//                    for (SysEvaluate sysEvaluate : evaluateList) {
//                        if (sysEvaluate.getIndentNumber().equals(tbOrders.getOrderNumber()) && sysEvaluate.getUserId().equals(tbOrders.getBuyerId())) {
                    return Result.success().put("data", evaluateList).put("total", evaluateList.size());
//                        }
//                    }
                }
            }
        }
        return Result.success().put("data", Collections.emptyList());
    }

    @Override
    public Result fakeDeletionTrends(Long trendsId) {
        Trends trends = baseMapper.selectById(trendsId);
        if (trends != null) {
            return Result.upStatus(baseMapper.updateByTrendsId(trendsId));
        }
        List<TrendsComment> trendsCommentList = trendsCommentDao.selectList(new QueryWrapper<TrendsComment>().eq("trends_id", trendsId));
        if (!trendsCommentList.isEmpty()) {
            trendsCommentDao.updateByTrendsId(trendsId);
        }
        return Result.error("删除失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteTrendsById(Long trendsId) {
        Trends trends = baseMapper.selectById(trendsId);
        if (trends != null) {
            List<TrendsComment> trendsCommentList = trendsCommentDao.selectList(new QueryWrapper<TrendsComment>().eq("trends_id", trendsId));
            if (!trendsCommentList.isEmpty()) {
                int result = trendsCommentDao.delete(new QueryWrapper<TrendsComment>().eq("trends_id", trendsId));
                if (result <= 0) {
                    return Result.error("删除失败");
                }
            }
            return Result.upStatus(baseMapper.deleteById(trendsId));
        }
        return Result.error("该动态不存在");
    }

    @Override
    public Result updateTrendsLike(Long trendsId, Integer virtualLikeCount) {
        Trends trends = baseMapper.selectById(trendsId);
        Integer likeCount = baseMapper.selectLikeCountByTrendsId(trendsId);
        if (trends != null) {
            trends.setVirtualLikeCount(virtualLikeCount);
            int newVirtualLikeCount = likeCount + virtualLikeCount;
            if (newVirtualLikeCount <= 0) {
                newVirtualLikeCount = 0;
            }
            trends.setTotalLikeCount(newVirtualLikeCount);
            return Result.upStatus(baseMapper.updateById(trends));
        }
        return Result.error("修改失败");
    }

    @Override
    public Result updateTrendsBrowse(Long trendsId, Integer virtualViewCount) {
        Trends trends = baseMapper.selectById(trendsId);
        if (trends != null) {
            trends.setVirtualViewCount(virtualViewCount);
            int newVirtualLikeCount = trends.getBrowseCount() + virtualViewCount;
            if (newVirtualLikeCount <= 0) {
                newVirtualLikeCount = 0;
            }
            trends.setTotalViewCount(newVirtualLikeCount);
            return Result.upStatus(baseMapper.updateById(trends));
        }
        return Result.error("修改失败");
    }

    @Override
    public Result getTrendsListByAdmin(Integer page, Integer limit, Long byUserId, TrendsVo trendsVo) {
        Page<TrendsVo> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        IPage<TrendsVo> trendsVos = baseMapper.getTrendsLists(pages, byUserId, trendsVo);
        for (TrendsVo record : trendsVos.getRecords()) {
            Goods goods = goodsDao.selectById(record.getGoodId());
            record.setGoods(goods);
        }
        return Result.success().put("data", trendsVos);
    }

    @Override
    public Result deleteTrends(Long userId, Long trendsId) {
        Trends trends = baseMapper.selectById(trendsId);
        if (userId != null) {
            if (!trends.getUserId().equals(userId)) {
                return Result.error("你无权操作");
            }
        }
        List<TrendsComment> trendsCommentList = trendsCommentDao.selectList(new QueryWrapper<TrendsComment>().eq("trends_id", trendsId));
        if (!trendsCommentList.isEmpty()) {
            trendsCommentDao.updateByTrendsId(trendsId);
        }
        return Result.upStatus(baseMapper.updateByTrendsId(trendsId));
    }

    @Override
    public Result examineTrends(Integer status, Long trendsId, String auditContent) {
        Trends trends = baseMapper.selectById(trendsId);
        if (status == 1) {
            trends.setStatus(1);
            trends.setIsListing(1);
        } else {
            trends.setStatus(2);
            trends.setIsListing(2);
        }
        trends.setAuditContent(auditContent);
        return Result.upStatus(baseMapper.updateById(trends));


    }


    @Override
    public TrendsVo getTrendsInfo(Long userId, Long byUserId, Long trendsId) {
        TrendsVo trendsVo = baseMapper.getTrendsInfo(byUserId, trendsId);
        if (byUserId != null && !byUserId.equals(trendsVo.getUserId())) {
            Trends trends = baseMapper.selectById(trendsId);
            if (trends != null) {
                trends.setBrowseCount(trends.getBrowseCount() + 1);
                baseMapper.updateById(trends);
            }
        }
        trendsVo.setCommentList(trendsCommentDao.getTrendsCommentList(byUserId, trendsId));
        return trendsVo;
    }

    @Override
    public Result addTrendsType(TrendsType trendsType) {
        if (trendsType.getId() != null) {
            // 检查类型名是否重复，但排除当前记录本身
            TrendsType existingType = trendsTypeDao.selectOne(
                    new QueryWrapper<TrendsType>()
                            .eq("type_name", trendsType.getTypeName())
                            .ne("id", trendsType.getId())
            );
            if (existingType != null) {
                return Result.error("类型名重复，请重新输入。");
            }
            return Result.upStatus(trendsTypeDao.updateById(trendsType));
        } else {
            if (trendsTypeDao.selectOne(new QueryWrapper<TrendsType>().eq("type_name", trendsType.getTypeName())) != null) {
                return Result.error("类型名重复,请重新输入");
            }
            trendsType.setCreateTime(new Date());
            return Result.upStatus(trendsTypeDao.insert(trendsType));
        }
    }

    @Override
    public Result deleteTrendsType(Long id) {
        TrendsType trendsType = trendsTypeDao.selectById(id);
        if (trendsType == null) {
            return Result.error("动态类型不存在");
        }
        return Result.upStatus(trendsTypeDao.deleteById(id));
    }

    @Override
    public Result selectTrendsTypeList(Integer page, Integer limit, TrendsType trendsType) {
        Page<TrendsType> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return Result.success().put("data", trendsTypeDao.selectTrendsTypeList(pages, trendsType));
    }

    @Override
    public Result selectTrendsTypeDetail(Long id) {
        TrendsType trendsType = trendsTypeDao.selectById(id);
        if (trendsType == null) {
            return Result.error("动态类型不存在");
        }
        return Result.success().put("data", trendsType);
    }

}
